export const convertTimeToAmPm = (time: `${string}:${string}`) => {
  const timeSplit = time.split(":");
  const hour = +timeSplit[0];
  if (hour > 12) {
    timeSplit[0] = `${hour - 12}`;
  }
  return `${timeSplit.join(":")}${
    hour >= 12 ? "PM" : "AM"
  }` as `${string}:${string}${"AM" | "PM"}`;
};

export const formatDateString = (date: `${string}-${string}-${string}`) =>
  `${date}`.split("-").join(".") as `${string}.${string}.${string}`;

export const formatLocaleDateText = (date: Date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  return `${year}年${month}月` as string;
}

export const formatDate = (date: Date, field = "day"): string => {
  const yearStr = date.getFullYear();
  const month = date.getMonth() + 1;
  const monthStr = fillWithZero(month, 2);
  const day = date.getDate();
  const dayStr = fillWithZero(day, 2);
  const strMap = {
    year: yearStr,
    month: `${yearStr} - ${monthStr}`,
    day: `${yearStr}-${monthStr}-${dayStr}`,
  };
  return strMap[field];
};

export const fillWithZero = (target: number, length: number): string => {
  return (Array(length).join("0") + target).slice(-length);
};

export const getTimeRemaining = (deadline) => {
  const total = Date.parse(deadline) - Date.parse(new Date().toString());
  const seconds =
    Math.floor((total / 1000) % 60) < 10
      ? "0" + Math.floor((total / 1000) % 60)
      : Math.floor((total / 1000) % 60);
  const minutes =
    Math.floor((total / 1000 / 60) % 60) < 10
      ? "0" + Math.floor((total / 1000 / 60) % 60)
      : Math.floor((total / 1000 / 60) % 60);
  const hours =
    Math.floor((total / (1000 * 60 * 60)) % 24) < 10
      ? "0" + Math.floor((total / (1000 * 60 * 60)) % 24)
      : Math.floor((total / (1000 * 60 * 60)) % 24);
  const days =
    Math.floor(total / (1000 * 60 * 60 * 24)) < 10
      ? "0" + Math.floor(total / (1000 * 60 * 60 * 24))
      : Math.floor(total / (1000 * 60 * 60 * 24));

  return {
    total,
    days,
    hours,
    minutes,
    seconds,
  };
};
